package com.tanhua.dubbo.api.interceptor;

import com.tanhua.dubbo.api.utils.JwtUtil;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器，拦截之后，解析token，拿到id
 * 拿完id，id存哪里？才能保证后续的业务可以去到你在这里解析的id？
 * 存在ThreadLocal中
 * ThreadLocal的作用：每个线程都会开辟一块独立的空间，多条线程开辟的ThreadLocal空间互相影响
 *                    一次请求就会开启一条线程
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * 前置拦截方法
     * @param request 请求
     * @param response 响应
     * @param handler 处理
     * @return
     * @throws Exception
     *
     * 拿到token，解析token，放入ThreadLocal
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 获取token
        String token = request.getHeader("authorization");
        //2 判断token是否有效
        if (!JwtUtil.verifyToken(token)){
            response.setStatus(401);
            return false;
        }

        //3 解析token
        Claims claims = JwtUtil.getClaims(token);
        Long id = Long.valueOf(claims.get("id").toString());
        String mobile = claims.get("mobile").toString();
        //4 构造User
        User user = new User(id, mobile);
        //5 放入ThreadLocal
        UserHolder.set(user);

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
